import React, { createRef, PureComponent } from 'react'
import {
  Select, Table, message,
} from 'antd'
import { connect, history } from '@umijs/max'
import _ from 'lodash'
import {
  InputSearch, ProTable, ProTableOperate, ProTableOptions,
} from '@/components'
import styles from './index.less'

const { Option } = Select
const { OperateItem } = ProTableOperate

const nodeTypeList = [
  { 1: '工作流' },
  { 12: '开始节点' },
  { 13: 'SQL' },
  // { 14: 'MapReduce' },
  // { 15: 'Impala' },
  { 16: 'Shell' },
  { 17: 'Python2' },
  { 18: 'Python3' },
  // { 19: 'Pyspark' },
  { 20: '离线同步' },
  { 21: '接口采集' },
  { 22: '数据质量' },
]

const nodeTypeFn = () => {
  const tempList = []
  nodeTypeList.forEach(item => {
    tempList.push({ text: Object.values(item)[0], value: Number(Object.keys(item)[0]) })
  })
  return tempList
}

const nodeTypeText = (nodeType) => {
  let resText = '- '
  nodeTypeList?.map(item => {
    if (`${nodeType}` === Object.keys(item)[0]) {
      resText = Object.values(item)[0]
    }
  })
  return resText
}

const cycleEnum = [
  { text: '分钟', value: 4, icon: 'icon-weiyunhang', color: 'hu-gray' },
  { text: '小时', value: 3, icon: 'icon-yunhangzhong_1', color: 'hu-blue' },
  { text: '天', value: 2, icon: 'icon-chenggong', color: 'hu-green'},
  { text: '周', value: 1, icon: 'icon-shibai1', color: 'hu-red' },
  { text: '月', value: 0, icon: 'icon-weiyunhang', color: 'hu-gray' },
]

@connect(({ operation }) => ({ ...operation }))
class TaskManage extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      filter_publishStatus: this.props?.filteredDefaultValue || [],
      taskStatus: null,
      execType: null,
      nodeName: this.props?.searchValue || '',
      query: {},
      forceUpdateKey: 0,
      expandedRowKeys: [],
      loading: false,
      modalVisible: false,
      runType: null,
      timeChecked: false,
      userId: '',
      userList: [],
      optTypeParams: null
    }
    this.tableRef = createRef()
  }

  componentWillMount() {
    const { proTableQuery = {}, filteredDefaultValue } = this.props
    this.setState({
      ...proTableQuery,
      query: {
        publishStatus: filteredDefaultValue?.[0] === 0 ? 0 : (filteredDefaultValue?.[0] || ''),
        nodeName: this.props?.searchValue || '',
        ...proTableQuery,
      },
    }, () => {
      this.saveTableQuery(true)
    })
  }

  componentDidMount() {
    this.queryUserList()
    // 清除传入的 pageNum、pageSize
    this.tableRef.current?.resetPagination()
  }

  getColumn = () => (
    [
      {
        title: '任务名称',
        key: 'name',
        width: '17%',
        render: (record) => (
          <span className={styles.link} onClick={() => { this.queryGetParentType(record?.id, record?.name) }}>{record?.name}</span>
        ),
      },
      {
        title: '发布状态',
        dataIndex: 'publishStatus',
        key: 'publishStatus',
        width: '9%',
        filters: [
          {
            text: '未发布',
            value: 0,
          },
          {
            text: '已发布',
            value: 1,
          },
        ],
        filteredValue: this.state.filter_publishStatus,
        // defaultFilteredValue: this.props?.filteredDefaultValue || [],
        // onFilter: (value, record) => {
        //   return record?.publishStatus === value
        // },
        render: (status) => (
          <>
            {
              status === 0 && (
                <><i className="iconfont icon-shibai1 hu-red" /> 未发布</>
              )
            }
            {
              status === 1 && (
                <><i className="iconfont icon-chenggong hu-green" /> 已发布</>
              )
            }
          </>
        ),
      },
      {
        title: '任务类型',
        dataIndex: 'nodeType',
        key: 'nodeType',
        width: '9%',
        filters: nodeTypeFn(),
        filteredValue: this.state.filter_nodeType,
        render: (nodeType) => (nodeTypeText(nodeType)),
      },
      {
        title: '发布时间',
        dataIndex: 'publishTime',
        key: 'publishTime',
        width: '14%',
        sorter: true,
        sortDirections: ['descend', 'ascend'], // 内容不要修改
      },
      // {
      //   title: '调度类型',
      //   dataIndex: 'execType',
      //   key: 'execType',
      //   width: '8%',
      //   filters: [
      //     {
      //       text: '手工执行',
      //       value: '0',
      //     },
      //     {
      //       text: '周期执行',
      //       value: '1',
      //     },
      //   ],
      //   onFilter: (value, record) => record.status.toString().indexOf(value) === 0,
      //   render: (execType) => (
      //     <>
      //       {execType === 0 && '手工执行'}
      //       {execType === 1 && '周期执行'}
      //     </>
      //   ),
      // },
      {
        title: '调度周期',
        key: 'cycle',
        width: '9%',
        filters: cycleEnum,
        filteredValue: this.state.filter_cycle,
        render: ({ cycle, scheduleInfo, haveChildren }) => {
          const cycleEnumObj = cycleEnum.filter(item => item.value === cycle)?.[0] || {}
          const signSta = !_.isEmpty(cycleEnumObj) && haveChildren
          return (
            <span title={signSta ? scheduleInfo : null} className={`${signSta ? styles.sign : ''}`}>{cycleEnumObj.text || '-'}</span>
          )
        },
      },
      {
        title: '冻结状态',
        // dataIndex: 'isLocked',
        key: 'isLocked',
        width: '13%',
        filters: [
          {
            text: '冻结', value: 1,
          },
          {
            text: '未冻结', value: 0,
          },
        ],
        filteredValue: this.state.filter_isLocked,
        // onFilter: (value, record) => record.isLocked === value,
        render: ({ isLocked }) => {
          return (
            <>
              {isLocked === 0 && '未冻结'}
              {isLocked === 1 && '冻结'}
            </>
          )
        }
      },
      {
        title: '责任人',
        dataIndex: 'userName',
        key: 'userName',
        width: '10%',
      },
      {
        title: '操作',
        key: 'action',
        width: '19%',
        render: (record) => {
          const {
            id, haveChildren, isLocked, runType, cycle,
          } = record
          return (
            <ProTableOptions size={4}>
              {
                (haveChildren || null) && (
                  <span onClick={() => {
                    this.saveTableQuery()
                    history.push(`/data-development/offline/operation-detail?nodeId=${id}`)
                  }}
                  >
                      详情
                    </span>
                )
              }
              <span
                onClick={() => {
                  this.saveTableQuery()
                  history.push(`/data-development/offline/operation-history?nodeId=${id}`)
                }}
              >历史任务
                </span>
              <span
                onClick={() => {
                  this.setState({
                    expandedRowKeys: [],
                  })
                  this.reRun(id)
                }}
              >
                  { runType === 0 ? '运行' : '重跑' }
                </span>
              {
                (cycle !== null && isLocked === 0 || null) && (
                  <span onClick={() => { this.handleChangeStatus([id], 1) }}>下线</span>
                )
              }
              {
                (isLocked === 1 || null) && (
                  <span onClick={() => { this.handleChangeStatus([id], 0) }}>上线</span>
                )
              }
            </ProTableOptions>
          )
        },
      },
    ]
  )

  queryUserList = () => {
    this.props.dispatch({
      type: 'operation/queryUserList',
      cb: (res) => {
        this.setState({
          userList: res || []
        })
      }
    })
  }

  fetchData = (isReset = true) => {
    const { userId, nodeName, query } = this.state
    isReset && this.tableRef?.current?.resetPageNum()
    const tempQuery = {}
    tempQuery.nodeName = nodeName || ''
    tempQuery.userId = userId || ''

    const queryTemp = _.cloneDeep(query)
    delete queryTemp.pageNum
    delete queryTemp.pageSize

    this.setState({
      query: {
        ...queryTemp,
        ...tempQuery,
      },
      expandedRowKeys: [],
    })
  }

  expandedRowRender = (record) => {
    const { id } = record
    const { subTablesData, expandedTableLoading } = this.state
    const copyColumns = this.getColumn() || []
    copyColumns.splice(0, 1)
    copyColumns.splice(copyColumns.length - 1, 1)
    const columns = [
      {
        title: '任务名称',
        dataIndex: 'name',
        key: 'name',
        width: '17%',
        render: (name, subRecord) => (
          <span>{name === "开始节点" ? <span>{name}</span> : <span className={styles.link} onClick={() => { this.queryGetParentType(subRecord?.id, name) }}>{name}</span>}</span>
        ),
      },
      ...copyColumns,
      {
        title: '操作',
        width: '19%',
        render: (subRecord) => {
          const { id, pid, runType, name } = subRecord || {}
          return (
            <ProTableOptions>
              {/*<span*/}
              {/*  onClick={() => {*/}
              {/*    this.saveTableQuery()*/}
              {/*    history.push(`/data-development/offline/operation-detail?nodeId=${id}`)*/}
              {/*  }}*/}
              {/*>*/}
              {/*  详情*/}
              {/*</span>*/}
              {
                (name !== '开始节点' || null) && (
                  <span
                    onClick={() => {
                      this.reRun(id, pid)
                    }}
                  >
                    { runType === 0 ? '运行' : '重跑' }
                  </span>
                )
              }
            </ProTableOptions>
          )
        },
      },
    ]

    return (
      <Table
        className={styles.sub_table}
        loading={!!expandedTableLoading?.[id]}
        rowKey="id"
        columns={columns}
        dataSource={subTablesData?.[id] || []}
        pagination={false}
        rowSelection={{
          type: 'checkbox',
          getCheckboxProps: () => ({
            disabled: true,
          }),
        }}
      />
    )
  }

  // 点击展开按钮发请求操作
  handleExpand = (expanded, record) => {
    const { id } = record
    if (expanded) {
      // setExpandedRowKeys([...expandedRowKeys, id])
      // setExpandedTableLoading({ [id]: true })
      this.setState((prevState) => ({
        expandedRowKeys: [...prevState.expandedRowKeys, id],
        expandedTableLoading: {
          ...prevState.expandedTableLoading,
          [id]: true,
        },
      }))
      this.querySubTask(id)
    } else {
      const { expandedRowKeys } = this.state
      const filterArr = expandedRowKeys.filter(item => item !== id)
      this.setState({
        expandedRowKeys: [...filterArr],
      })
    }
  }

  // 获取子任务
  querySubTask = (id) => {
    this.props.dispatch({
      type: 'operation/queryChildren',
      params: { nodeId: id },
      cb: (data = []) => {
        let spliceArr = []
        if (data?.length > 0) {
          data?.some((item, index) => {
            if (item.name === '开始节点') {
              if (index !== 0) {
                spliceArr = data?.splice(index, 1)
              }
            }
          })
        }

        const formatArr = [...spliceArr, ...data]

        this.setState((prevState) => ({
          subTablesData: {
            ...prevState.subTablesData,
            [id]: formatArr,
          },
          expandedTableLoading: {
            ...prevState.expandedTableLoading,
            [id]: false,
          },
        }))
      },
    })
  }

  resetExpandedRowKeys = () => {
    this.setState({
      expandedRowKeys: [],
    })
  }

  // 上线下线
  handleChangeStatus = (idArr, isLocked, optTypeParams) => {
    const selectedRowKeys = idArr?.length ? idArr : this.tableRef?.current?.state?.selectedRowKeys
    if (selectedRowKeys.length < 1) {
      message.warning('请至少选择一条数据')
      return null
    }
    let idsStr = ''
    selectedRowKeys.map((item) => {
      if (idsStr !== '') idsStr += ','
      idsStr += item
      return null
    })

    this.setState({
      optTypeParams,
      loading: true,
    })

    this.props.dispatch({
      type: 'operation/queryChange',
      params: {
        isLocked,
        nodeIds: idsStr,
      },
      cb: (res) => {
        this.setState({
          optTypeParams: null,
          loading: false,
        })
        const { msg, status } = res
        if (status === 200) {
          message.success('操作成功')
          this.forceUpdateFn()
        } else {
          message.error(msg || '服务端错误')
        }
      }
    })
  }

  // 重跑
  reRun = (id, pid = undefined) => {
    this.setState({ loading: true })
    this.props.dispatch({
      type: 'operation/queryRestart',
      params: {
        nodeId: id,
      },
      cb: (res) => {
        const { status, msg } = res || {}
        this.setState({
          loading: false,
        })
        if (status === 200) {
          message.success('操作成功')
          if (pid !== undefined) {
            this.querySubTask(pid)
          } else {
            this.fetchData(false)
          }
        } else {
          message.error(msg || '系统异常，请稍后重试~')
        }
      },
    })
  }

  forceUpdateFn = () => {
    this.setState((prevSta) => ({
      forceUpdateKey: prevSta.forceUpdateKey + 1,
    }))
  }

  // 保存表格此次请求的参数
  saveTableQuery = (isClear = false) => {
    const { proTableQuery } = this.tableRef?.current?.state || {}
    this.props.dispatch({
      type: 'operation/saveTableQuery',
      params: {
        proTableQuery: isClear ? {} : proTableQuery,
        activeTabKey: isClear ? '1' : '2',
      },
    })
  }

  queryGetParentType = (nodeId, nodeName) => {
    this.props.dispatch({
      type: 'operation/queryGetParentType',
      params: {
        nodeId,
      },
      cb: (res) => {
        const { msg, status, data } = res
        if (status === 200) {
          if (data === 1) {
            // 作业开发
            history.push(`/data-development/offline/script-development?nodeId=${nodeId}&nodeName=${nodeName}`)
          } else {
            history.push(`/data-development/offline/workflow-development?nodeId=${nodeId}&nodeName=${nodeName}`)
          }
        } else {
          message.error(msg || '服务端错误')
        }
      },
    })
  }

  handleTableChange = (pagination, filters, sorter) => {
    const queryFilter = {}
    for (const f in filters) {
      if (filters[f]) {
        queryFilter[f] = filters[f]?.join(',')
      }
      this.setState({ [`filter_${f}`]: filters[f] })
    }

    if (sorter?.order) {
      queryFilter.order = sorter?.order === 'descend' ? 'desc' : 'asc'
      queryFilter.orderField = sorter?.field
    }

    const { userId, nodeName, query } = this.state
    this.tableRef?.current?.resetPageNum()

    const tempQuery = {}
    tempQuery.nodeName = nodeName || ''
    tempQuery.userId = userId || ''

    this.setState({
      query: {
        // ...queryTemp,
        ...tempQuery,
        ...queryFilter,
      },
      expandedRowKeys: [],
    })
  }

  render() {
    const {
      loading, forceUpdateKey, query, expandedRowKeys, userList, nodeName, optTypeParams, userId,
    } = this.state
    const rowSelection = {
      type: 'checkbox',
    }

    return (
      <div className={styles.taskManage}>
        <ProTableOperate style={{ marginBottom: 12 }}>
          <OperateItem>
            <span>责任人</span>
            <Select
              allowClear
              value={userId}
              onChange={(value) => {
                this.setState({
                  userId: value || '',
                }, () => { this.fetchData() })
              }}
            >
              {
                userList?.map(item => (
                  <Option key={item.id} value={item.id}>{item.username}</Option>
                ))
              }
            </Select>
          </OperateItem>
          <OperateItem align="left">
            <InputSearch
              value={nodeName}
              placeholder="请输入任务名称进行搜索"
              onChange={(e) => {
                this.setState({
                  nodeName: e.target.value,
                })
              }}
              onSearch={this.fetchData}
            />
          </OperateItem>
        </ProTableOperate>

        <ProTable
          ref={this.tableRef}
          loading={loading}
          key={forceUpdateKey}
          url="/api/v1/offlineDev/operation/v2/taskManager/page"
          query={query}
          rowKey="id"
          columns={this.getColumn()}
          expandedRowKeys={expandedRowKeys}
          expandable={{
            expandedRowRender: this.expandedRowRender,
            onExpand: this.handleExpand,
            rowExpandable: record => record.haveChildren,
          }}
          resetExpandedRowKeys={this.resetExpandedRowKeys}
          rowSelection={rowSelection}
          onChange={this.handleTableChange}
          bulkOperation={[
            {
              title: '上线',
              loading: optTypeParams === 0 ? loading : false,
              onClick: (params) => {this.handleChangeStatus(params, 0, 0)}
            },
            {
              title: '下线',
              onClick: (params) => {this.handleChangeStatus(params, 1)}
            },
          ]}
        />


        {/* 需求改变，代码隐藏 */}
        {/*<Modal*/}
        {/*  title="重跑"*/}
        {/*  visible={modalVisible}*/}
        {/*  destroyOnClose*/}
        {/*  onCancel={() => {*/}
        {/*    this.setState({*/}
        {/*      modalVisible: false,*/}
        {/*    })*/}
        {/*  }}*/}
        {/*>*/}
        {/*  <Form*/}
        {/*    ref={this.dataSourceForm}*/}
        {/*    labelCol={{ span: 4 }}*/}
        {/*    wrapperCol={{ span: 13 }}*/}
        {/*    autoComplete="off"*/}
        {/*  >*/}
        {/*    <Item*/}
        {/*      label="任务名称"*/}
        {/*      name="tableName"*/}
        {/*    >*/}
        {/*      <Input placeholder="请输入任务名称" />*/}
        {/*    </Item>*/}

        {/*    <Item*/}
        {/*      label="重跑类型"*/}
        {/*      name="runType"*/}
        {/*    >*/}
        {/*      <Select*/}
        {/*        allowClear*/}
        {/*        showSearch*/}
        {/*        placeholder="请选择重跑类型"*/}
        {/*        onChange={this.handleRunType}*/}
        {/*      >*/}
        {/*        <Option key="1">直接重跑</Option>*/}
        {/*        <Option key="2">自定义重跑</Option>*/}
        {/*      </Select>*/}
        {/*    </Item>*/}
        {/*    {*/}
        {/*      runType === '2' && (*/}
        {/*        <Item*/}
        {/*          label="业务日期"*/}
        {/*          labelCol={{ span: 4 }}*/}
        {/*          wrapperCol={{ span: 20 }}*/}
        {/*        >*/}
        {/*          <Row gutter={8} className={styles.date_wrap}>*/}
        {/*            <Col span={16}>*/}
        {/*              <Form.Item*/}
        {/*                className={styles.date_picker}*/}
        {/*                name="date"*/}
        {/*                colon={false}*/}
        {/*                rules={*/}
        {/*                  [{ required: true, message: '请选择业务日期' }]*/}
        {/*                }*/}
        {/*              >*/}
        {/*                <DatePicker onChange={this.handleDate} style={{ width: '100%' }} />*/}
        {/*              </Form.Item>*/}
        {/*            </Col>*/}
        {/*            <Col span={8}>*/}
        {/*              <Form.Item style={{ paddingLeft: 10 }}>*/}
        {/*                <Checkbox onChange={this.handleCheckbox}>选择时分</Checkbox>*/}
        {/*                <Tooltip placement="topLeft" title="产生指定的业务日期内，指定的时间范围内计划开始运行的任务，例如：业务日期：2019-01-01~2019-01-03 具体时间：01:30~03:00 表示：2019-01-01~2019-01-03期间内，每天的01:30~03:00开始运行的任务，时间范围为闭区间，时间范围选择了23:59后，计划开始时间23:59开始运行的任务会进行重跑 。"><i className="iconfont icon-yiwentishi" /></Tooltip>*/}
        {/*              </Form.Item>*/}
        {/*            </Col>*/}
        {/*          </Row>*/}
        {/*        </Item>*/}
        {/*      )*/}
        {/*    }*/}

        {/*    {*/}
        {/*      timeChecked && (*/}
        {/*        <Item*/}
        {/*          label="具体时间"*/}
        {/*          name="time"*/}
        {/*        >*/}
        {/*          <TimePicker.RangePicker style={{ width: '100%' }} />*/}
        {/*        </Item>*/}
        {/*      )*/}
        {/*    }*/}
        {/*  </Form>*/}
        {/*</Modal>*/}
      </div>
    )
  }
}

export default TaskManage
